<?php


namespace App\Model;


use App\Helpers\Helpers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Symfony\Component\Console\Helper\Helper;

/**
 * App\Model\Cart
 *
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $goods_id 商品ID
 * @property int $number 商品数量
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart whereGoodsId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart whereNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Cart whereUserId($value)
 * @property-read \App\Model\Goods $goods
 */
class Cart extends Model
{

    protected $table = 'cart';

    protected $fillable = ['user_id', 'goods_id', 'number'];

    /**
     * @param Goods $goods
     * @author thanatos thanatos915@163.com
     */
    public static function AddGoodsCart($goods)
    {
        $user_id = Helpers::getUserId();
        $cart = static::where('user_id', $user_id)
            ->where('goods_id', $goods->id)->first();

        if (empty($cart)) {
            $cart = static::create([
                'user_id' => $user_id,
                'goods_id' => $goods->id,
                'number' => 0,
            ]);
        }

        $cart->number += 1;
        $cart->save();
    }

    public function goods()
    {
        return $this->belongsTo(Goods::class);
    }


}

